package com.chat.server;

import com.chat.entity.*;
import com.chat.util.JwtUtils;
import io.netty.channel.ChannelHandlerContext;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 分配对象给不同的服务
 */
public class BaseServerManager implements ServerManager {

    UserServer userServer;


    public BaseServerManager() {
        try {
            userServer = new UserServer();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public DataPackage allocateObject(DataPackage o) throws IOException {
        //登录和注册服务
        DataPackagerServer dataPackagerServer = null;
        if(o.getAction()==ServerAction.LOGIN||o.getAction()==ServerAction.REGISTER) {
            dataPackagerServer = new VerifyServer();
            DataPackage result = dataPackagerServer.run(o);
            result.setEventId(o.getEventId());
            return result;
        }


        //token验证
        String token = o.getToken();
        if(token==null||!JwtUtils.verify(token)){
            return DataPackage.failResponse(token,ServerAction.NO);
        }

        //获取服务类型
        //比如User,Room,File等
        String serverName = o.getAction().name().split("_")[1];
        switch (serverName){
            case "USER":
                dataPackagerServer = new UserServer();
                break;

            case "USERS":
                dataPackagerServer = new UserServer();
                break;

            case "ROOM":
                dataPackagerServer = new RoomServer();
                break;

            case "ROOMS":
                dataPackagerServer = new RoomServer();
                break;

            case "MESSAGE":
                dataPackagerServer = new MessageServer();
                break;

            case "FILE":
                dataPackagerServer = new FileServer();
                break;

            case "FILES":
                dataPackagerServer = new FileServer();
                break;
        }
        System.out.println("服务："+dataPackagerServer.getClass().getName());
        DataPackage result = dataPackagerServer.run(o);
        result.setEventId(o.getEventId());
        return result;
    }

    /**
     * 进行身份验证
     * @return
     */
    public boolean verify(DataPackage dataPackage){
        String token = dataPackage.getToken();
        if(token==null||token.equals("")||!JwtUtils.verify(token))
            return false;
        return true;
    }

}
